package com.wlz.file.threadfile;
 
import java.io.Closeable;
import java.io.File;
import java.io.IOException;
import java.io.RandomAccessFile;
import java.nio.channels.FileChannel;
import java.util.concurrent.CountDownLatch;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class BlogTest {
 
 
    public static void main(String[] args) {
        long time = System.currentTimeMillis();
        String url = "/Users/wlz/Desktop/HUMTEST_30-40.zip";
        String destPackagePath = url.substring(0, url.lastIndexOf("."));
        File destFilePath = new File(destPackagePath);
        if (!destFilePath.exists()) {
            destFilePath.mkdirs();
        }
        String copyUrl = destPackagePath + url.substring(url.lastIndexOf("/"));
 
        try{
            File testFile = new File(url);
            long size = testFile.length();
 
            //定义每个线程处理的文件大小
            long subFileCount = 512 * 1024 * 1024;// 512M
            //定义线程池  控制同时处理的线程数 可以避免磁盘占用过高
            ExecutorService fixedThreadPool = Executors.newFixedThreadPool(50);
            //计算需要多少线程处理
            long threadCount = size % subFileCount == 0 ? size/subFileCount : size/subFileCount +1;
 
            System.out.println("需要线程数:"+threadCount);
 
            CountDownLatch cdl = new CountDownLatch((int) threadCount);
 
            for(long i=0,position=0; i<threadCount; i++,position=i*subFileCount){
                if(size - position < subFileCount){
                    subFileCount = size - position;
                }
                fixedThreadPool.execute(new FileThread(url, copyUrl, position, subFileCount, cdl));
            }
            cdl.await();
            System.out.println(cdl.getCount());
            System.out.println("文件复制完毕");
            fixedThreadPool.shutdown();
        } catch (Exception e){
            e.printStackTrace();
        }
        System.out.println("time : " + (System.currentTimeMillis() - time));
    }

    //关闭流
    public static void closeStream(Closeable...closeables){
        for (Closeable closeable : closeables) {
            if (closeable != null){
                try {
                    closeable.close();
                } catch (IOException e) {
                    e.printStackTrace();
                }
            }
        }
    }
}